//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by 胡阳 on 16/5/23.
//  Copyright © 2016年 young4ever. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    let WBAppKey = "3399256692"
    let WBAppSecret = "9afae57e602c45ea5d42c665b131febd"
    let WBRedirectUrl = "http://www.vcredit.com"
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 初始化导航条
        navigationItem.title = "SinaWeibo"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(OAuthViewController.close))
        
        //获取未授权的requestToken
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectUrl)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    func close()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK:- 懒加载
    private lazy var webView : UIWebView = {
    
        let wv = UIWebView()
        wv.delegate = self
        return wv
    }()
}

extension OAuthViewController : UIWebViewDelegate {

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        // 授权成功
        print(request.URL?.absoluteString)
        let urlStr = request.URL!.absoluteString
        
        // 1.判断是否是授权回调页面, 不是就继续加载网页
        if !urlStr.hasPrefix(WBRedirectUrl) {
            return true
        }
        
        // 2.判断是否授权成功
        let codeStr = "code="
        if request.URL!.query!.hasPrefix(codeStr) {
            // 授权成功
            // 1.取出已经授权成功的requestToken
            let code = request.URL!.query!.substringFromIndex(codeStr.endIndex)
            print("授权成功 + \(code)")
            
            // 2.利用授权的requestToken换取accessToken
            getAccessToken(code)
        }else {
            // 授权失败
            print("授权失败")
            
            SVProgressHUD.showInfoWithStatus("您已取消授权!")
        }
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
//        SVProgressHUD.showInfoWithStatus("正在加载...")
        SVProgressHUD.show()
    }

    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
    /**
     换取accessToken
     
     - parameter code: 已经授权成功的requestToken
     */
    private func getAccessToken(code: String)
    {
        // 1. 拿到请求路径
        let path = "oauth2/access_token"
        // 2. 封装参数
        let params = ["client_id" : WBAppKey,
                      "client_secret" : WBAppSecret,
                      "grant_type" : "authorization_code",
                      "code" : code,
                      "redirect_uri" : WBRedirectUrl]
        // 3.发送post请求
//        weak var weakSelf = self
        NetworkTools.shareNetworkTools().POST(path, parameters: params, success: { (_, JSON) in
            
            /**
             结论:
             
             同一个用户对于同一个应用多次授权的access_token是一样的,每个access_token都有过期时间
             对于开发者来说时间为5年
             对于其他用户来说为3天
             // 2.00ylTdnDqwvCiD69a4714309_e_BrD
             // 2.00ylTdnDqwvCiD69a4714309_e_BrD
             */
                print(JSON)
            // 1.获取授权模型<字典转模型>
            let user = UserAccount(dict: JSON as![String : AnyObject])
            print(user)
            
            /*
             存储数据的几种方式:
             plist: 特点只能存储系统自带的数据类型<数组,字典...>
             将对象转换为json之后写入文件 --> 在公司中已经开始使用
             偏好设置: 本质为plist文件
             归档: 可以存储自定义的对象
             数据库: 存储大容量数据 , 效率比较高
             */
            
            // 2.获取用户信息
            user.loadUserInfo({ (account, error) in
                
                if account != nil && error == nil {
                
                    account?.saveAccount()
                    
                    // 去主页
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: false)
                    
                    self.close()
                    
                }else {
                    SVProgressHUD.showErrorWithStatus("网络不给力...")
                }
            })
            
            }) { (_, error) in
                print(error)
                SVProgressHUD.showErrorWithStatus("网络不给力...")
        }
    }
}
